package com.joysuch.wwyt.util;

import com.google.common.collect.Lists;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZhangDong
 * @Date 2020/6/24 14:56
 */
public class PageableUtil {

    /**
     * 针对结果集分页
     */
    public static <T> List<T> getList(Pageable pageable, List<T> list) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        return getList(pageNumber, pageSize, list);
    }

    public static <T> List<T> getList(int pageNumber, int pageSize, List<T> list) {
        int startIndex = pageNumber * pageSize;
        int endIndex = pageNumber * pageSize + pageSize;
        if (list.size() < startIndex) {
            return Lists.newArrayList();
        }
        if (list.size() - startIndex < pageSize) {
            return list.subList(startIndex, list.size());
        }
        return list.subList(pageNumber * pageSize, endIndex);
    }

    public static <T> List<List<T>> groupByList(List<T> sourceDatas, int pageSize) {
        // 分组集合
        List<List<T>> groupLists = new ArrayList<List<T>>();
        // 分组数据
        List<T> tempDatas = new ArrayList<T>();
        if (sourceDatas != null && pageSize > 0) {
            for (int i = 0; i < sourceDatas.size(); i++) {
                if (i % pageSize == 0) {
                    if (!tempDatas.isEmpty()) {
                        groupLists.add(tempDatas);
                    }
                    tempDatas = new ArrayList<T>();
                    tempDatas.add(sourceDatas.get(i));

                } else {
                    tempDatas.add(sourceDatas.get(i));
                }
            }
        }
        if (!tempDatas.isEmpty()) {
            groupLists.add(tempDatas);
        }
        return groupLists;
    }

}
